﻿using Microsoft.AspNetCore.Components;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json.Bson;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using vite_core.EF_Core.EFDbcontext;
using vite_ef.Repositories.EntityFrameworkCore;
using vitecore.Module;

namespace vite_ef
{
    [InjectOn(ServiceLifetime.Scoped, Scheme = InjectScheme.None, Own = true)]
    public class UnitOfWork 
    {
        private readonly ViteNetDbContext _db;

        public UnitOfWork(ViteNetDbContext db)
        {
            _db = db;
        }

        public async Task<IDbContextTransaction> BeginTranAsync(CancellationToken ctk)
        {

            if (_db.Database.CurrentTransaction == null)
              return  await _db.Database.BeginTransactionAsync(ctk);

            return _db.Database.CurrentTransaction;
        }

        public async Task CommitTranAsync(CancellationToken ctk)
        {
            if (_db.Database.CurrentTransaction != null)
                await _db.Database.CurrentTransaction.CommitAsync(ctk);
            // 不需要释放dbContext 这是因为.NET Core中的依赖注入容器（DI容器）负责管理DbContext的生命周期，一般是scope
           // await DisposeAsync();
        }

        public void Dispose()
        {
             _db.Dispose(); 
        }

        public async Task DisposeAsync()
        {
            if (_db != null)
            { 
                await _db.DisposeAsync();
            }
        }

        public async Task RollBack(CancellationToken ctk) 
        {
            if (_db.Database.CurrentTransaction != null)
                await _db.Database.CurrentTransaction.RollbackAsync(ctk);
        }
    }
}
